package com.java.work01.servlet;

import com.java.work01.service.LoginServiceImpl;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;

@WebServlet(name = "LoginServlet", value = "/LoginServlet")
public class LoginServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String auto = request.getParameter("auto"); //是否自动登录

        if (new LoginServiceImpl().login(username, password)) {//如果登录成功
            request.getSession().setAttribute("username", username);
            if (auto == null) {//未勾选自动登录
                Cookie cookie = new Cookie("auto", null);
                cookie.setMaxAge(60 * 60 * 24);//cookie有效时间
                cookie.setPath(request.getContextPath() + "/");
                response.addCookie(cookie);
            } else {//勾选自动登录
                Cookie cookie = new Cookie("auto", username + "_" + password);
                cookie.setMaxAge(60 * 60 * 24);//cookie有效时间
                cookie.setPath(request.getContextPath() + "/");
                response.addCookie(cookie);
            }
            //登录成功，跳转
            response.sendRedirect("index.jsp");
        } else {
            //未登录成功，重新登录
            response.sendRedirect("login.jsp");
        }
    }
}
